package com.eascs.web.o2o.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.aging.service.SysOrgService;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.entity.O2oPlatformRegional;
import com.eascs.web.o2o.web.form.LoanBeforeForm;
import com.eascs.web.o2o.web.service.ProvinceNameData;
import com.eascs.web.o2o.web.service.ReportForLoanBeforeService;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;

/**
 * 业务运营分析（贷前数据）
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="/loanBefore")
public class ReportForLoanBeforeController extends BaseMasterViewController {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	SysOrgService sysOrgService;
	
	@Autowired
	ProvinceNameData provinceNameData;
	
	@Autowired
	ReportForLoanBeforeService reportForLoanBeforeService;

	@RequestMapping(value="/index")
	public String searchLoanBefore(LoanBeforeForm entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "reportForLoanBefore");
		String o2oUrl = "/restLoanBefore/loanBefore";
		if(entity != null) {
			String createDateStart = entity.getCreateDateStart();
			String createDateEnd = entity.getCreateDateEnd();
			String nsStartDateStart = entity.getNsStartDateStart();
			String nsStartDateEnd = entity.getNsStartDateEnd();
			String ssBankName = entity.getSsBankName();
			String zxBankName = entity.getZxBankName();
			String provinceName = entity.getProvinceName();
			String brandName = entity.getBrandName();
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "createDateStart", createDateStart);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "createDateEnd", createDateEnd);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "nsStartDateStart", nsStartDateStart);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "nsStartDateEnd", nsStartDateEnd);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "ssBankName", ssBankName);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "zxBankName", zxBankName);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "provinceName", provinceName);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "brandName", brandName);
			o2oUrl = o2oUrl + "&o2oIndex=";
		} else {
			o2oUrl = o2oUrl + "&o2oIndex=";
		}
		List<O2oPlatformRegional> proList = provinceNameData.getProvinceNameData();
		ViewContext.put("vo", entity);
		ViewContext.put("o2ourl", o2oUrl);
		ViewContext.put("proList", proList);
		return "report/loanBefore";
	}
	
	@RequestMapping(value="/download")
	public void downloadReport(LoanBeforeForm entity, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		String createdateStart = entity.getCreateDateStart();
		String createdateEnd = entity.getCreateDateEnd();
		entity.setPageSize(Integer.MAX_VALUE);

		PageResult<Object[]> pageResult = reportForLoanBeforeService.loanBefore(entity);
		String       path    = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s       = new StringBuffer();
		String       outPath = s.append(path).append("/report-loanBefore.xls").toString();
		
		String date;
		if(createdateStart.equals(createdateEnd)) {
			date = createdateStart;
		} else {
			date = createdateStart + "至" +createdateEnd;
		}
		try {
			String outfile = date + "业务运营分析（贷前数据）.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes     = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists()) throw new RuntimeIOException("file not found");

			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");

			// 开始的表格，行，列
			int sheetIndex  = 0;
			int rowIndex    = 2;
			int columnIndex = 0;
			// 包含的列
			int col = 14;
			// 需要统计的列
			int[]  arr = {};
			
			BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(pageResult.getData(), col, arr, Arrays.asList(new String(bytes, "UTF-8")), sheetIndex, rowIndex, columnIndex);
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), MonReportController.class.getResourceAsStream("/excelTemplate/report-loanBefore.xls"), bankRowWriteHandler);

		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} 
	}
}
